import Taro, {Component} from "@tarojs/taro";
import {View, Text, ScrollView} from "@tarojs/components";
import "./index.less";
import Note from "../../commponents/note/note";
import Feed from "../../commponents/feed/feed";
import Api from "../../api/api";
import dayjs from "dayjs";
import Loadmore from "../../commponents/load-more/load-more";
import {AtToast} from "taro-ui";
import NavBar from "../../commponents/nav-bar/nav-bar";
import {getGlobal} from "../../api/globalData";

export default class Index extends Component {
  config = {
    navigationBarTitleText: "首页",
    enablePullDownRefresh: true,
    onReachBottomDistance: 400
  };

  constructor() {
    super(...arguments);
    this.state = {
      docList: [],
      currentTab: 0,
      scrollLeft: 0,
      categoryList: [{keyword: "", name: "最新"}],
      pageNo: 1,
      keyword: "",
      loadingMore: "",
      refreshSuccess: false
    };
  }

  async componentDidMount() {
    this.setState({loadingMore: "loading"});
    const docList = await this.getList("", 1, 20);
    const categoryList = await this.getCategoryList();
    this.setState({
      loadingMore: "",
      docList: docList,
      categoryList: categoryList
    });
    this.initCategoryDocList(this.state.currentTab, docList);
  }

  // 下拉刷新监听事件
  async onPullDownRefresh() {
    let docList = await this.getList(
      this.state.categoryList[this.state.currentTab].keyword,
      1,
      20
    );
    this.setState({
      docList: docList
    });
    this.initCategoryDocList(this.state.currentTab, docList);
    Taro.stopPullDownRefresh();
    this.setState({refreshSuccess: true});
  }

  async onReachBottom() {
    if (this.state.loadingMore === "noMore") {
      return;
    }
    this.setState({loadingMore: "loading"});
    let docs = await this.getList(
      this.state.keyword,
      this.state.pageNo + 1,
      20
    );
    let docList = this.state.docList;
    docs.forEach(v => {
      docList.push(v);
    });
    this.setState({
      docList: docList
    });
  }

  async getList(keyword, pageNo, pageSize) {
    let d = await Api.docList(keyword, 1, pageNo, pageSize);
    let res = d.data.data;
    let list = res.list;
    list.forEach(v => {
      v.createdAt = dayjs(v.created_at).format("YYYY-MM-DD HH:mm");
    });
    this.setState({
      pageNo: pageNo,
      keyword: keyword,
      loadingMore: res.hasNext ? "" : "noMore"
    });
    return list;
  }

  async getCategoryList() {
    let {data} = await Api.categoryList();
    let arr = this.state.categoryList;
    if (data.success) {
      data.data.forEach(v => {
        arr.push(v);
      });
    }
    return arr;
  }

  initCategoryDocList(tabIndex, docList) {
    let items = this.state.categoryList;
    items[tabIndex].docList = docList;
    this.setState({categoryList: items});
  }

  checkCor(current) {
    if (current >= 3) {
      this.setState({scrollLeft: current * 60});
    } else if (current >= 2) {
      this.setState({scrollLeft: current * 10});
    } else {
      this.setState({scrollLeft: 0});
    }
  }

  toTop() {
    Taro.pageScrollTo({
      scrollTop: 0,
      duration: 0
    });
  }

  async switchNav(e) {
    Taro.showLoading();
    this.refreshClose();
    const current = Number(e.target.dataset.current);
    if (this.state.currentTab === current) {
      this.toTop();
      Taro.hideLoading();
      return false;
    } else {
      this.setState({currentTab: current});
      this.checkCor(current);
      const list = this.state.categoryList[current].docList;
      if (list) {
        this.toTop();
        this.setState({
          docList: list,
          pageNo: 1,
          keyword: this.state.categoryList[current].keyword
        });
        Taro.hideLoading();
        return;
      }
      let docList = await this.getList(e.target.dataset.keyword, 1, 20);
      this.setState({
        docList: docList
      });
      this.initCategoryDocList(current, docList);
      this.toTop();
      Taro.hideLoading();
    }
  }

  refreshClose() {
    this.setState({refreshSuccess: false});
  }

  render() {
    let loadNode;
    if (this.state.loadingMore === "loading") {
      loadNode = (
        <View className="weui-loadmore">
          <View className="weui-loading"/>
          <View className="weui-loadmore__tips">正在加载</View>
        </View>
      );
    } else if (this.state.loadingMore === "noMore") {
      loadNode = (
        <View className="weui-loadmore weui-loadmore_line">
          <View className="weui-loadmore__tips weui-loadmore__tips_in-line">
            没有更多了
          </View>
        </View>
      );
    } else {
      loadNode = "";
    }

    return (
      <View>
        <NavBar showBox={false} showSearch/>
        <View className="container" >
          <ScrollView
            scrollX="true"
            className="tab-h"
            scrollLeft={this.state.scrollLeft}
            scrollWithAnimation="true"
            style={{marginTop:`${getGlobal("navBarHeight")+44}px`}}
          >
            {this.state.categoryList.map((item, index) => {
              return (
                <View
                  key={index}
                  className={`tab-item ${
                    this.state.currentTab === index ? "active" : ""
                    }`}
                  data-current={index}
                  onTap={this.switchNav.bind(this)}
                  data-keyword={item.keyword}
                >
                  {item.name}
                </View>
              );
            })}
          </ScrollView>
          <View>
            <View className="note-list">
              {this.state.docList.map((item, index) => {
                return <Feed note={item} showDesc="true" from="0" key={index}/>;
              })}
            </View>
          </View>
          <Loadmore loadingMore={this.state.loadingMore}/>
          <AtToast
            isOpened={this.state.refreshSuccess}
            text="刷新成功"
            duration={1500}
            onClose={this.refreshClose.bind(this)}
          />
        </View>
      </View>
    );
  }
}
